package com.poi.demo.parser;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>Word文字解析器</p>
 *
 * @author Allen Yang
 * @datetime 2021/11/18 14:53
 */
@Setter
@Getter
public class WordParagraphParser extends WordContentParser {

    private Map<String, String> textReplaceMap;

    public WordParagraphParser(InputStream in, Map<String, String> textReplaceMap) {
        super(in);
        this.textReplaceMap = textReplaceMap;
    }

    public WordParagraphParser(XWPFDocument doc, Map<String, String> textReplaceMap) {
        super(doc);
        this.textReplaceMap = textReplaceMap;
    }

    public WordParagraphParser(InputStream in) {
        super(in);
    }

    public WordParagraphParser(XWPFDocument doc) {
        super(doc);
    }

    public WordParagraphParser(String path) {
        super(path);
    }


    @Override
    public XWPFDocument replace() {
        if (Objects.isNull(getDoc())) {
            throw new RuntimeException(ERR_MSG_DOC_NOT_LOADED);
        }
        if (MapUtils.isEmpty(textReplaceMap)) {
            throw new RuntimeException(ERR_MSG_PARAM_NOT_INITIALIZED);
        }
        List<XWPFParagraph> xwpfParagraphs = getDoc().getParagraphs();
        xwpfParagraphs.forEach(xwpfParagraph -> {
            List<XWPFRun> runs = xwpfParagraph.getRuns();
            runs.forEach(run -> {
                String str = run.getText(run.getTextPosition()); //获取run中的字符串
                if (StringUtils.isNotEmpty(str)) {
                    for (Map.Entry<String, String> entry: textReplaceMap.entrySet()) {
                        str = str.replace(entry.getKey(), entry.getValue());
                    }
                }
                run.setText(str, 0);
            });
        });

        return getDoc();
    }
}
